package baiqitun.stupro.project.service.impl;

import baiqitun.stupro.common.exception.enums.support.NotFoundExceptionEnum;
import baiqitun.stupro.common.entity.impl.SysFile;
import baiqitun.stupro.common.exception.support.NotFoundException;
import baiqitun.stupro.common.service.system.SysFileService;
import baiqitun.stupro.common.service.support.MyServiceImpl;
import baiqitun.stupro.common.util.MyPageUtil;
import baiqitun.stupro.project.core.news.SysProjectNews;
import baiqitun.stupro.project.core.news.constant.SysProjectNewsActionEnum;
import baiqitun.stupro.project.core.news.constant.SysProjectNewsObjectTypeEnum;
import baiqitun.stupro.project.core.news.repository.SysProjectNewsRepository;
import baiqitun.stupro.project.entity.SysProjectFile;
import baiqitun.stupro.project.mapper.SysProjectFileMapper;
import baiqitun.stupro.project.service.SysProjectFileService;
import baiqitun.stupro.project.service.SysProjectService;
import baiqitun.stupro.security.entity.SysUser;
import baiqitun.stupro.security.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 项目文件表 服务实现类
 * </p>
 *
 * @author kedaji
 * @since 2020-04-23
 */
@Service
public class SysProjectFileServiceImpl extends MyServiceImpl<SysProjectFileMapper, SysProjectFile> implements SysProjectFileService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private SysProjectService sysProjectService;
    @Autowired
    private SysProjectNewsRepository sysProjectNewsRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void uploadToProject(MultipartFile file, InputStream is, String projectId, String createBy) throws IOException {
        sysProjectService.checkNotFound(projectId, new NotFoundException(NotFoundExceptionEnum.PROJECT_NOT_FOUND));
        SysUser user = sysUserService.getUserByUsername(createBy);
        if (user == null){
            throw new NotFoundException(NotFoundExceptionEnum.RELATION_DEPART_USER_NOT_FOUND);
        }
        SysFile f = new SysFile();
        f.setFilename(file.getOriginalFilename()).setUserId(user.getId()).setCreateBy(createBy);
        sysFileService.save(f, file.getInputStream());

        SysProjectFile projectFile = new SysProjectFile();
        projectFile.setProjectId(projectId).setFileId(f.getId()).setCreateBy(createBy);
        save(projectFile);

        // 保存项目动态
        SysProjectNews projectNews = new SysProjectNews();
        projectNews.setProjectId(projectId).setUserId(user.getId())
                .setObjectName(f.getFilename())
                .setAction(SysProjectNewsActionEnum.CREATE.name()).setObjectType(SysProjectNewsObjectTypeEnum.FILE.name()).setObjectType(SysProjectNewsObjectTypeEnum.FILE.name())
                .setObjectId(f.getId()).setCreateBy(createBy);
        sysProjectNewsRepository.save(projectNews);
    }

    @Transactional(readOnly = true, rollbackFor = Exception.class)
    @Override
    public IPage<SysFile> pageFileByProjectId(String projectId, int pageNo, int pageSize) {
        return pageUserFileByProjectId(projectId, null, pageNo, pageSize);
    }

    @Transactional(readOnly = true, rollbackFor = Exception.class)
    @Override
    public IPage<SysFile> pageUserFileByProjectId(String projectId, String username, int pageNo, int pageSize) {
        // 获取项目的文件
        sysProjectService.checkNotFound(projectId, new NotFoundException(NotFoundExceptionEnum.PROJECT_NOT_FOUND));
        SysProjectFile queryProjectFile = new SysProjectFile();
        queryProjectFile.setProjectId(projectId).setCreateBy(username);
        IPage<SysProjectFile> queryProjectFilePage = new Page<>();


        queryProjectFilePage.setCurrent(pageNo).setSize(pageSize);
        IPage<SysProjectFile> relationPage = page(queryProjectFilePage, new QueryWrapper<>(queryProjectFile));

        List<SysFile> files = new LinkedList<>();
        for (SysProjectFile relation: relationPage.getRecords()){
            SysFile existedFile = sysFileService.getExistedEntity(relation.getFileId(), new NotFoundException(NotFoundExceptionEnum.FILE_NOT_FOUND));
            files.add(existedFile);
        }

        int count = count(new QueryWrapper<>(queryProjectFile));
        IPage<SysFile> filePage = new Page<>();
        filePage.setSize(pageSize).setCurrent(pageNo).setRecords(files).setTotal(count).setPages(MyPageUtil.getTotalPage(count, relationPage.getPages()));
        return filePage;
    }
}
